package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.autoconfigure.PageHelperProperties;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.BeanHelper;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@Api(tags="菜品管理")
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Autowired
    private PageHelperProperties pageHelperProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addDish(DishDTO dishDTO) {
        //1.保存菜品基本信息
        Dish dish = BeanHelper.copyProperties(dishDTO, Dish.class);
        //1.2.更改状态
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);

        //2.保存菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }

        dishFlavorsMapper.insertBatch(flavors);
    }

    //分页查询
    @Override
    public PageResult page(DishPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //执行查询
        List<DishVO> dishVOList = dishMapper.list(pageQueryDTO);

        Page<DishVO> pageList = (Page<DishVO>) dishVOList;
        return new PageResult(pageList.getTotal(), pageList.getResult());
    }

    //批量删除
    @Override
    public void deleteByIds(List<Long> ids) {
        //1.查看菜品是否起售，如果起售就抛出业务异常
        Long count = dishMapper.countByStatus(ids);
        if(count > 0){
            throw new BusinessException(MessageConstant.DISH_ON_SALE);
        }

        //2.查看菜品是否关联了套餐，如果关联了就抛出业务异常
        List<Long> dishCount = setMealDishMapper.getByDishId(ids);
        if (!CollectionUtils.isEmpty(dishCount)){
            throw new BusinessException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.删除菜品也要删除菜品口味数据
        dishMapper.deleteByIds(ids);
        dishFlavorsMapper.deleteByDishId(ids);
    }

    //根据id查询菜品和对应的口味数据
    @Override
    public DishVO getInfo(Long id) {
        //1.查询菜品的基本数据
        Dish dish = dishMapper.getById(id);

        //2.查询菜品的口味数据
        List<DishFlavor> dishFlavors = dishFlavorsMapper.getByDishId(id);

        //3.组装数据
        DishVO dishVO = BeanHelper.copyProperties(dish, DishVO.class);
        if(dishVO != null){
            dishVO.setFlavors(dishFlavors);
        }

        return dishVO;
    }

    //修改菜品
    @Override
    public void update(DishDTO dishDTO) {
        //1.修改菜品基本信息
        Dish dish = BeanHelper.copyProperties(dishDTO, Dish.class);
        dishMapper.update(dish);

        //2.修改菜品口味数据 （先删后加）
        //2.1先删除
        dishFlavorsMapper.deleteByDishId(Collections.singletonList(dishDTO.getId()));

        //2.2 再添加
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor ->{
            dishFlavor.setDishId(dishDTO.getId());
        });
        dishFlavorsMapper.insertBatch(flavors);
    }


    //启售停售
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }

    //根据分类id查询菜菜品
    @Override
    public List<Dish> list(Long categoryId, String name) {
        return dishMapper.getList(categoryId, name);
    }

    //根据分类id查询菜品返回DishVO
    @Override
    public List<DishVO> selectByCategoryId(Long categoryId) {
        String resdisDishKey = "dish:cache" + categoryId;

        //1.先在缓存里查询，如果缓存里有数据，就返回数据
        List<DishVO> dishVOList = (List<DishVO>)redisTemplate.opsForValue().get(resdisDishKey);
        if (!CollectionUtils.isEmpty(dishVOList)){
            log.info("缓存中有数据, 命中");
            return dishVOList;
        }

        //2.如果缓存中没有数据，就查询数据库
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        dishVOList = dishMapper.getBycategoryId(dish);


        //3.将查询到的数据放入缓存
        redisTemplate.opsForValue().set(resdisDishKey, dishVOList);
        log.info("缓存中没有数据, 查询数据库");
        return dishVOList;
    }


}
